from odoo import models, fields, api
from odoo.exceptions import UserError
from odoo.tools.safe_eval import safe_eval
import datetime


class XlsxReportDateWizard(models.TransientModel):
    _name = 'xlsx.report.date.wizard'
    _description = 'Xlsx Report Date Filter Wizard'

    report_config_id = fields.Many2one(
        'xlsx.report.config',
        string='Report Configuration',
        required=True,
        ondelete='cascade',
        help="The report configuration linked to this wizard."
    )

    start_date = fields.Date(string='Start Date', help="Filter records from this date.")

    end_date = fields.Date(string='End Date', help="Filter records up to this date.")

    def action_generate_report(self):
        self.ensure_one()
        report_config = self.report_config_id

        base_domain = []
        if report_config.domain:
            try:
                base_domain = safe_eval(report_config.domain)
                if not isinstance(base_domain, list):
                    raise ValueError("Domain must be a list.")
            except Exception as e:
                raise UserError(f"Report configuration contains an invalid Domain: {e}")

        date_domain = []
        date_field_name = report_config.date_field_id.name

        target_model_obj = self.env[report_config.model_id.model]
        create_date_field_obj = target_model_obj._fields.get(date_field_name)

        if not create_date_field_obj:
            raise UserError(
                f"The model '{report_config.model_id.model}' does not have a '{date_field_name}' field for date filtering.")

        # 處理起始日期
        if self.start_date:
            if report_config.date_field_id.ttype == 'datetime':
                start_datetime = datetime.datetime.combine(self.start_date, datetime.time.min)
                date_domain.append((date_field_name, '>=', start_datetime))
            else:  # date 字段
                date_domain.append((date_field_name, '>=', self.start_date))

        # 處理結束日期
        if self.end_date:
            if report_config.date_field_id.ttype == 'datetime':
                # 對於 datetime 字段，通常的做法是加一天再用 '<' (小於)，
                # 這樣能包含結束日期的所有時間點，且避免浮點數精度問題
                end_datetime = datetime.datetime.combine(self.end_date, datetime.time.max)
                date_domain.append((date_field_name, '<=', end_datetime))
            else:  # date 字段
                date_domain.append((date_field_name, '<=', self.end_date))

        # 3. 合併所有 Domain
        combined_domain = base_domain + date_domain

        # 4. 根據合併後的 Domain 搜尋目標記錄 ID
        target_model_name = report_config.model_id.model
        if not target_model_name:
            raise UserError("Target model is not specified in the report configuration.")

        if target_model_name not in self.env.registry:
            raise UserError(f"Model '{target_model_name}' does not exist or is not loaded.")

        filtered_records = self.env[target_model_name].search(combined_domain)
        if not filtered_records:
            raise UserError("No records found matching the specified criteria.")
        obj = report_config.action_report_id.with_context(lang='en_US').report_action(filtered_records.ids)

        return obj
        # return {
        #     'type': 'ir.actions.client',
        #     'tag': 'action_multi',  # 這個特殊的 tag 讓前端執行 params.actions 中的列表
        #     'params': {
        #         'actions': [
        #             obj,  # 首先觸發報表下載或預覽的動作
        #             {'type': 'ir.actions.act_window_close'},  # 然後關閉當前精靈窗口的動作
        #         ],
        #     },
        # }
